import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'generated/native_video_cache_api.g.dart';
import 'cache_stability_manager.dart';
import 'cache_performance_monitor.dart';

/// 缓存进度监听器类型定义
typedef CacheProgressListener = void Function(String url, double progress);

/// 缓存状态监听器类型定义
typedef CacheStatusListener = void Function(String url, CacheStatus status);

/// 缓存错误监听器类型定义
typedef CacheErrorListener = void Function(String url, String error);

/// CacheService的默认实现
class _DefaultCacheService implements CacheService {
  @override
  Future<void> startCache(String url) async {
    return NativeVideoCacheManager.startCache(url);
  }

  @override
  Future<void> stopCache(String url) async {
    return NativeVideoCacheManager.stopCache(url);
  }
}

/// Native视频缓存管理器
///
/// 提供视频缓存的核心功能，包括初始化、URL代理、缓存管理等
class NativeVideoCacheManager {
  static final NativeVideoCacheApi _api = NativeVideoCacheApi();
  static final MethodChannel _debugChannel =
      const MethodChannel('native_video_cache/debug');

  // 添加EventChannel来接收原生平台的缓存事件
  static const EventChannel _cacheEventChannel =
      EventChannel('native_video_cache/cache_events');
  static StreamSubscription<dynamic>? _cacheEventSubscription;

  // 事件监听器列表
  static final List<CacheProgressListener> _progressListeners = [];
  static final List<CacheStatusListener> _statusListeners = [];
  static final List<CacheErrorListener> _errorListeners = [];

  static bool _initialized = false;

  /// 初始化缓存系统
  ///
  /// [config] 缓存配置，包括最大缓存大小、缓存目录等
  ///
  /// 必须在使用其他功能前调用此方法
  static Future<void> initialize(CacheConfig config) async {
    if (_initialized) {
      debugPrint('NativeVideoCacheManager: 已经初始化，跳过重复初始化');
      return;
    }

    try {
      // 设置调试日志处理
      // _debugChannel.setMethodCallHandler((call) async {
      //   if (call.method == 'log') {
      //     debugPrint('iOS Native: ${call.arguments}');
      //   }
      // });

      await _api.initialize(config);
      await _api.setCacheListener();

      // 启动缓存事件监听
      _startCacheEventListener();

      _initialized = true;

      // 设置依赖注入
      CacheStabilityManager.instance.setCacheService(_DefaultCacheService());

      debugPrint('NativeVideoCacheManager: 初始化成功');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 初始化失败 - $e');
      rethrow;
    }
  }

  /// 启动缓存事件监听器
  static void _startCacheEventListener() {
    _cacheEventSubscription =
        _cacheEventChannel.receiveBroadcastStream().listen(
      (dynamic event) {
        try {
          final Map<String, dynamic> eventData =
              Map<String, dynamic>.from(event);
          final String eventType = eventData['type'] as String;
          final String url = eventData['url'] as String;

          switch (eventType) {
            case 'progress':
              final double progress = (eventData['progress'] as num).toDouble();
              _onCacheProgressChanged(url, progress);
              break;
            case 'status':
              final int statusIndex = eventData['status'] as int;
              final CacheStatus status = CacheStatus.values[statusIndex];
              _onCacheStatusChanged(url, status);
              break;
            case 'error':
              final String error = eventData['error'] as String;
              _onCacheError(url, error);
              break;
          }
        } catch (e) {
          debugPrint('NativeVideoCacheManager: 处理缓存事件失败 - $e');
        }
      },
      onError: (error) {
        debugPrint('NativeVideoCacheManager: 缓存事件监听错误 - $error');
      },
    );
  }

  /// 获取代理URL用于播放器
  ///
  /// [originalUrl] 原始视频URL
  ///
  /// 返回可用于播放器的代理URL，播放器使用此URL时会自动进行缓存
  static Future<String> getProxyUrl(String originalUrl) async {
    _ensureInitialized();

    try {
      final proxyUrl = await _api.getProxyUrl(originalUrl);
      debugPrint(
          'NativeVideoCacheManager: 获取代理URL成功 - 原始:$originalUrl -> 代理:$proxyUrl');
      return proxyUrl;
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 获取代理URL失败 - $e');
      rethrow;
    }
  }

  /// 开始缓存视频
  ///
  /// [url] 视频URL
  ///
  /// 主动开始缓存指定的视频，即使没有播放
  static Future<void> startCache(String url) async {
    _ensureInitialized();

    try {
      await _api.startCache(url);

      // 记录性能监控事件
      CachePerformanceMonitor.instance.recordCacheStart(url);

      debugPrint('NativeVideoCacheManager: 开始缓存 - $url');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 开始缓存失败 - $e');
      rethrow;
    }
  }

  /// 停止缓存视频
  ///
  /// [url] 视频URL
  static Future<void> stopCache(String url) async {
    _ensureInitialized();

    try {
      await _api.stopCache(url);
      debugPrint('NativeVideoCacheManager: 停止缓存 - $url');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 停止缓存失败 - $e');
      rethrow;
    }
  }

  /// 获取缓存信息
  ///
  /// [url] 视频URL
  ///
  /// 返回包含缓存状态、进度、大小等信息的[CacheInfo]对象
  static Future<CacheInfo> getCacheInfo(String url) async {
    _ensureInitialized();

    try {
      final info = await _api.getCacheInfo(url);
      return info;
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 获取缓存信息失败 - $e');
      rethrow;
    }
  }

  /// 检查是否已缓存
  ///
  /// [url] 视频URL
  ///
  /// 返回true表示视频已完全缓存
  static Future<bool> isCached(String url) async {
    _ensureInitialized();

    try {
      final cached = await _api.isCached(url);
      return cached;
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 检查缓存状态失败 - $e');
      return false;
    }
  }

  /// 清理所有缓存
  static Future<void> clearAllCache() async {
    _ensureInitialized();

    try {
      await _api.clearAllCache();
      debugPrint('NativeVideoCacheManager: 清理所有缓存成功');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 清理所有缓存失败 - $e');
      rethrow;
    }
  }

  /// 清理指定URL的缓存
  ///
  /// [url] 视频URL
  static Future<void> clearCache(String url) async {
    _ensureInitialized();

    try {
      await _api.clearCache(url);
      debugPrint('NativeVideoCacheManager: 清理缓存成功 - $url');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 清理缓存失败 - $e');
      rethrow;
    }
  }

  /// 获取总缓存大小
  ///
  /// 返回当前总缓存大小（字节）
  static Future<int> getTotalCacheSize() async {
    _ensureInitialized();

    try {
      final size = await _api.getTotalCacheSize();
      return size;
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 获取总缓存大小失败 - $e');
      return 0;
    }
  }

  /// 添加缓存进度监听器
  ///
  /// [listener] 进度变化监听器
  static void addProgressListener(CacheProgressListener listener) {
    _progressListeners.add(listener);
  }

  /// 移除缓存进度监听器
  ///
  /// [listener] 要移除的监听器
  static void removeProgressListener(CacheProgressListener listener) {
    _progressListeners.remove(listener);
  }

  /// 添加缓存状态监听器
  ///
  /// [listener] 状态变化监听器
  static void addStatusListener(CacheStatusListener listener) {
    _statusListeners.add(listener);
  }

  /// 移除缓存状态监听器
  ///
  /// [listener] 要移除的监听器
  static void removeStatusListener(CacheStatusListener listener) {
    _statusListeners.remove(listener);
  }

  /// 添加缓存错误监听器
  ///
  /// [listener] 错误监听器
  static void addErrorListener(CacheErrorListener listener) {
    _errorListeners.add(listener);
  }

  /// 移除缓存错误监听器
  ///
  /// [listener] 要移除的监听器
  static void removeErrorListener(CacheErrorListener listener) {
    _errorListeners.remove(listener);
  }

  /// 清理所有监听器
  static void clearAllListeners() {
    _progressListeners.clear();
    _statusListeners.clear();
    _errorListeners.clear();
  }

  /// 释放资源
  ///
  /// 应用退出时调用，清理资源和监听器
  static Future<void> dispose() async {
    if (!_initialized) return;

    try {
      // 取消缓存事件监听
      await _cacheEventSubscription?.cancel();
      _cacheEventSubscription = null;

      await _api.removeCacheListener();
      clearAllListeners();
      _initialized = false;
      debugPrint('NativeVideoCacheManager: 资源释放成功');
    } catch (e) {
      debugPrint('NativeVideoCacheManager: 资源释放失败 - $e');
    }
  }

  /// 格式化文件大小显示
  ///
  /// [bytes] 字节数
  ///
  /// 返回格式化的文件大小字符串，如"1.5 MB"
  static String formatFileSize(int bytes) {
    const int kb = 1024;
    const int mb = kb * 1024;
    const int gb = mb * 1024;

    if (bytes < kb) return '$bytes B';
    if (bytes < mb) return '${(bytes / kb).toStringAsFixed(1)} KB';
    if (bytes < gb) {
      return '${(bytes / mb).toStringAsFixed(1)} MB';
    }
    return '${(bytes / gb).toStringAsFixed(1)} GB';
  }

  /// 确保已初始化
  static void _ensureInitialized() {
    if (!_initialized) {
      throw StateError('NativeVideoCacheManager未初始化，请先调用initialize()方法');
    }
  }

  /// 内部方法：分发缓存进度事件
  static void _onCacheProgressChanged(String url, double progress) {
    // 记录性能监控事件
    CachePerformanceMonitor.instance.recordProgressUpdate(url, progress);

    // 通知所有监听器
    for (final listener in _progressListeners) {
      try {
        listener(url, progress);
      } catch (e) {
        debugPrint('NativeVideoCacheManager: 进度监听器异常 - $e');
      }
    }
  }

  /// 内部方法：分发缓存状态事件
  static void _onCacheStatusChanged(String url, CacheStatus status) {
    // 记录性能监控事件
    if (status == CacheStatus.cached) {
      CachePerformanceMonitor.instance.recordCacheComplete(url);
    }

    // 通知所有监听器
    for (final listener in _statusListeners) {
      try {
        listener(url, status);
      } catch (e) {
        debugPrint('NativeVideoCacheManager: 状态监听器异常 - $e');
      }
    }
  }

  /// 内部方法：分发缓存错误事件
  static void _onCacheError(String url, String error) {
    // 记录性能监控事件
    CachePerformanceMonitor.instance.recordCacheFailure(url, error);

    // 通知所有监听器
    for (final listener in _errorListeners) {
      try {
        listener(url, error);
      } catch (e) {
        debugPrint('NativeVideoCacheManager: 错误监听器异常 - $e');
      }
    }
  }
}
